package vn.csp.gameportal;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.ActionBar.TabListener;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.devspark.sidenavigation.SideNavigationView;

public class MainActivity extends SherlockFragmentActivity {
	ActionBar mActionBar;
	ViewPager mPager;
	Tab tab;
    TabListener tabListener;
    @Override
	  public boolean onCreateOptionsMenu(Menu menu) {
    	
	    com.actionbarsherlock.view.MenuInflater inflater = getSupportMenuInflater();
	    inflater.inflate(R.menu.main_menu,menu);
	    /**
	     * Thanh tìm kiếm ./.
	     */
	    SearchView searchView = (SearchView) menu.findItem(R.id.tim_kiem).getActionView();
	    int id = searchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
        final TextView textView = (TextView) searchView.findViewById(id);
        textView.setTextColor(Color.WHITE);
//        textView.setText("Nhập tên game cần tìm.");

        final SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextChange(String newText) {
                // Do something
//            	thongBao(newText);
                return true;
            }

            @Override
            public boolean onQueryTextSubmit(String query) {
                // Do something
            	thongBao(query);
                return true;
            }
        };
        
        searchView.setOnQueryTextListener(queryTextListener);
        
        return true;
	  }
    @Override
	  public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
//	    case R.id.tai_lai:
//	    	Toast.makeText(getApplicationContext(),"Đang cập nhật danh sách game.", Toast.LENGTH_LONG).show();
//	    	//Lấy vị trí trước khi tải lại Activity
//	    	int x = mActionBar.getSelectedNavigationIndex();
//	    	Intent intent = new Intent(getApplicationContext(),MainActivity.class);
//	    	intent.putExtra("viTriTabTruocKhiTaiLai", x);
//	    	startActivity(intent);
//	      break;
	      /**
	       * Bật menu trượt ngang
	       */
		    case android.R.id.home:
		    	SideNavigationView sideNavigationView = (SideNavigationView)findViewById(R.id.side_navigation_view);
		    	sideNavigationView.setMenuItems(R.menu.side_navigation);
		    	sideNavigationView.toggleMenu();
		        return true;
	    }
	    return true;
	  }
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        /**
         * Khi màn hình xoay ngang thì xóa toàn bộ Title
         */
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        	mActionBar.setTitle("");
    		mActionBar.setSubtitle("");
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        	mActionBar.setTitle(Html.fromHtml("<font color='#ffffff'>Game Potal</font>"));
			mActionBar.setSubtitle(Html.fromHtml("<font color='#ffffff'>Tất cả</font>"));
        }
    }
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mActionBar = getSupportActionBar();
		mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		
		mActionBar.setDisplayShowTitleEnabled(true);
	//	mActionBar.setDisplayShowHomeEnabled(true);
		
		mActionBar.setDisplayHomeAsUpEnabled(true);
		// Nếu nàn hình đang quay xoay thì xóa Title
		if (getResources().getConfiguration().orientation == 2) {
        	mActionBar.setTitle("");
    		mActionBar.setSubtitle("");
        } 
		else{
			/**
			 * Set tiêu đề tại thanh action bar màu trắng dùng Html.fromHtml
			 */
			mActionBar.setTitle(Html.fromHtml("<font color='#ffffff'>Game Potal</font>"));
			mActionBar.setSubtitle(Html.fromHtml("<font color='#ffffff'>Tất cả</font>"));
		}
		
		mPager = (ViewPager) findViewById(R.id.pager);
		
		// Activate Fragment Manager
		FragmentManager fm = getSupportFragmentManager();
		// Capture ViewPager page swipes
		ViewPager.SimpleOnPageChangeListener ViewPagerListener = new ViewPager.SimpleOnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				super.onPageSelected(position);
				mActionBar.setSelectedNavigationItem(position);
			}
		};
		mPager.setOnPageChangeListener(ViewPagerListener);
		// Locate the adapter class called ViewPagerAdapter.java
		ViewPagerAdapter viewpageradapter = new ViewPagerAdapter(fm);
		// Set the View Pager Adapter into ViewPager
		mPager.setAdapter(viewpageradapter);
		
		/** tabListener  */
		 tabListener = new ActionBar.TabListener() {
			@Override
			public void onTabSelected(Tab tab, FragmentTransaction ft) {
				mPager.setCurrentItem(tab.getPosition());
			}
			@Override
			public void onTabUnselected(Tab tab, FragmentTransaction ft) {
			}

			@Override
			public void onTabReselected(Tab tab, FragmentTransaction ft) {
			}
		};
		/** Tab Phân Loại */
		tab = mActionBar.newTab().setText("Phân Loại").setTabListener(tabListener);
		mActionBar.addTab(tab);
		
		/** Tab Tải Nhiều  */
		tab = mActionBar.newTab().setText("Tải Nhiều").setTabListener(tabListener);
		mActionBar.addTab(tab);

		/** Tab Mới Nhất  */
		tab = mActionBar.newTab().setText("Mới Nhất").setTabListener(tabListener);
		mActionBar.addTab(tab);

		/** Tab Hay Nhất  */
		tab = mActionBar.newTab().setText("Hay Nhất").setTabListener(tabListener);
		mActionBar.addTab(tab);
		
		/**
		 * Mặc định vô là Tab Tải Nhiều
		 */
		mActionBar.setSelectedNavigationItem(1);
		/**
		 * Xử lí Tình huống Refresh lại danh sách game
		 */
		int tabIndex = getIntent().getIntExtra("viTriTabTruocKhiTaiLai",-1);
		if(tabIndex != -1){
			// Di chuyển đến Tab tương ứng vị trí
			mActionBar.setSelectedNavigationItem(tabIndex);
		}
	}
	@Override
	public View onCreateView(String name, Context context, AttributeSet attrs) {
		return super.onCreateView(name, context, attrs);
	}
	/**
     * @param noiDung : thông điệp cần hiển thị.
     * Dùng trong tình huống muốn hiện các thông báo
     */
    public void thongBao(String noiDung){
    	Toast.makeText(getApplicationContext(), noiDung, Toast.LENGTH_LONG).show();
    }
    @Override
    public void onBackPressed(){
    	DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
    	    @Override
    	    public void onClick(DialogInterface dialog, int which) {
    	        switch (which){
    	        case DialogInterface.BUTTON_POSITIVE:
    	            break;
    	        case DialogInterface.BUTTON_NEGATIVE:
//    	        	moveTaskToBack(true);	
    	        	finish();
    	            break;
    	        }
    	    }
    	};
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setMessage("Bạn có muốn thoát ứng dụng không ?").setPositiveButton("Không", dialogClickListener)
    	    .setNegativeButton("Đồng ý", dialogClickListener).show();
    }
    /**
     * Xử lí nút Menu Button
     */
    @Override
    public boolean onKeyDown(int keycode, KeyEvent event ) {
    	
	if(keycode == KeyEvent.KEYCODE_MENU){
		SideNavigationView sideNavigationView = (SideNavigationView)findViewById(R.id.side_navigation_view);
		sideNavigationView.setMenuItems(R.menu.side_navigation);
		sideNavigationView.toggleMenu();
	}
//    	
//	  LayoutInflater factory = LayoutInflater.from(this);
//	  final View loginView = factory.inflate(R.menu.custom_menu, null);
//     if(keycode == KeyEvent.KEYCODE_MENU){
//      AlertDialog.Builder dialogBuilder 
//      = new AlertDialog.Builder(this);
////      .setTitle("Menu");
//      dialogBuilder.setView(loginView);
//      dialogBuilder.create().show();
//     }
     return super.onKeyDown(keycode,event);  
    }
}
